package com.hxd.otc.module.wallet.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hxd.otc.MainActivity;
import com.hxd.otc.R;
import com.hxd.otc.base.BaseApplication;
import com.hxd.otc.base.BaseFragment;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.wallet.activity.CoinRechargeActivity;
import com.hxd.otc.module.wallet.activity.CoinWithdrawActivity;
import com.hxd.otc.module.wallet.activity.OtcToNormalAccountActivity;
import com.hxd.otc.module.wallet.activity.WalletActivity;
import com.hxd.otc.module.wallet.adapter.OtcAssestAdapter;
import com.hxd.otc.module.wallet.bean.WalletCurrencyBean;
import com.hxd.otc.module.wallet.contract.OtcAssestContract;
import com.hxd.otc.module.wallet.presenter.OtcAssestPresenter;
import com.hxd.otc.utils.LogUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 包  名 :  com.hxd.otc.module.wallet.fragment
 * 类  名 :  OtcAssestFragment
 * 作  者 :  zjl
 * 时  间 :  2019/4/9 9:49
 * 描  述 :  ${TODO}
 */
public class OtcAssestFragment extends BaseFragment<OtcAssestPresenter> implements OtcAssestContract.IView {

    @BindView(R.id.cb_hide_zore)
    CheckBox cbHideZore;

    @BindView(R.id.rl_hide)
    RelativeLayout rlHide;

    @BindView(R.id.et_coin)
    EditText etCoin;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    View errorView;

    View notDataView;

    LinearLayout llOtc;

    LinearLayout llNormal;

    TextView tvRefresh;

    TextView tvBuyAgain;

    OtcAssestAdapter adapter;

    public static final int REQUEST_CODE_WITHDRAW = 1;//提币
    public static final int REQUEST_CODE_RECHARG = 2;//充值
    public static final int REQUEST_CODE_TRANSER = 3;//划转

    private int pos;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_otc_assest;
    }

    @Override
    protected void initView() {
        pos = getArguments().getInt("pos");
        if (pos == 0) {
            mPresenter.setNorInfo(false);
        } else {
            mRefreshLayout.setEnableRefresh(false);
//            mPresenter.setNorInfo(true);
            rlHide.setVisibility(View.GONE);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doLoadData(true);
            }
        });
        notDataView = getLayoutInflater().inflate(R.layout.otc_empty_view, (ViewGroup) recyclerView.getParent(), false);
        tvBuyAgain = notDataView.findViewById(R.id.tv_buy_again);
        llOtc = notDataView.findViewById(R.id.ll_otc);
        llNormal = notDataView.findViewById(R.id.ll_normal);
        if (pos == 0) {
            tvBuyAgain.setVisibility(View.VISIBLE);
            llOtc.setVisibility(View.VISIBLE);
            llNormal.setVisibility(View.GONE);
        } else {
            tvBuyAgain.setVisibility(View.GONE);
            llOtc.setVisibility(View.GONE);
            llNormal.setVisibility(View.VISIBLE);
        }

        errorView = getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) recyclerView.getParent(), false);
        tvRefresh = errorView.findViewById(R.id.tv_refresh);

        if (pos == 0) {
            tvRefresh.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mRefreshLayout.autoRefresh(0, 10, 1);
                }
            });
        }

        tvBuyAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("isSkipToDealPage", true);
                $startActivity(MainActivity.class, bundle, true);
            }
        });


    }

    private void initAdapter() {
        if (adapter == null) {
            adapter = new OtcAssestAdapter();
            adapter.setPos(pos);
            adapter.setOnItemListener(new OtcAssestAdapter.OnAssestItemListener() {
                @Override
                public void OnWalletIntoClick(WalletCurrencyBean bean) {
                    if (TextUtils.isEmpty(bean.getName())) {
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("walletInfo", (Serializable) mPresenter.getOtcWalletInfoBeans());
                    for (int i = 0; i < ((WalletActivity) getActivity()).getOtcFragment().mPresenter.getOtcWalletInfoBeans().size(); i++) {
                        if (bean.getName().equals(((WalletActivity) getActivity()).getOtcFragment().mPresenter.getOtcWalletInfoBeans().get(i).getName())) {
                            bundle.putInt("pos", i);
                        }
                    }
//                    bundle.putSerializable("normalWalletInfo", (Serializable) ((WalletActivity) getActivity()).getNormalFragment().mPresenter.getNorWalletInfoBeans());
                    Intent intent = new Intent(getActivity(), OtcToNormalAccountActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, REQUEST_CODE_TRANSER);
                }

                @Override
                public void OnRechargeCoinClick(WalletCurrencyBean bean) {

                    if (TextUtils.isEmpty(bean.getName())) {
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("coinType", bean.getName());
                    bundle.putString("coinId", bean.getId());
                    Intent intent = new Intent(getActivity(), CoinRechargeActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, REQUEST_CODE_RECHARG);
                }

                @Override
                public void OnEextractCoinClick(WalletCurrencyBean bean) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("walletCurrencyBean", bean);
                    Intent intent = new Intent(getActivity(), CoinWithdrawActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, REQUEST_CODE_WITHDRAW);
                }
            });
            recyclerView.setAdapter(adapter);
        }
    }

    @Override
    protected void initData() {

//        if (BaseApplication.isHideZeroAssests) {
//            cbHideZore.setChecked(true);
//        }
        initAdapter();
        if (pos == 1) {
            adapter.setEmptyView(notDataView);
        } else if (pos == 0) {
            if (BaseApplication.isHideZeroAssests) {
                cbHideZore.setChecked(true);
            }
            mRefreshLayout.autoRefresh(0, 10, 1);
        }

    }

    @Override
    protected void initEvent() {
        cbHideZore.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                LogUtils.e("======onCheckedChanged==========" + isChecked);
                BaseApplication.isHideZeroAssests = isChecked;
//                if (pos == 0) {
//                    ((WalletActivity) getActivity()).getNormalFragment().setCheckStable(isChecked);
//                } else if (pos == 1) {
//                    ((WalletActivity) getActivity()).getOtcFragment().setCheckStable(isChecked);
//                }
                hideZeroAssests(pos);
            }
        });

        etCoin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (pos == 0 && (mPresenter.getOtcWalletInfoBeans() == null || mPresenter.getOtcWalletInfoBeans().size() < 0)) {
                    showToast(getString(R.string.no_data));
                    return;
                }

                if (pos == 1 && (mPresenter.getNorWalletInfoBeans() == null || mPresenter.getNorWalletInfoBeans().size() < 0)) {
                    showToast(getString(R.string.no_data));
                    return;
                }

                if (TextUtils.isEmpty(s.toString().trim())) {
                    LogUtils.e("=====1=======s=====" + s.toString().trim());
                    searchCoin(s.toString().trim().toUpperCase(), false);
                    return;
                }

                searchCoin(s.toString().trim().toUpperCase(), true);

            }
        });

        etCoin.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //当actionId == XX_SEND 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    InputMethodManager manager = (InputMethodManager) etCoin.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (manager != null) {
                        manager.hideSoftInputFromWindow(etCoin.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        manager.hideSoftInputFromInputMethod(etCoin.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    return true;
                }
                return false;
            }
        });
    }

    List<WalletCurrencyBean> otcBeans;
    List<WalletCurrencyBean> norBeans;

    public void hideZeroAssests(int position) {
        LogUtils.e("==pos : " + pos + " , position : " + position);
        if (!TextUtils.isEmpty(etCoin.getText().toString().trim())) {
            return;
        }
        if (BaseApplication.isHideZeroAssests) {
            if (pos == 0) {
                otcBeans = new ArrayList<>();
                if (mPresenter.getOtcWalletInfoBeans() != null && mPresenter.getOtcWalletInfoBeans().size() > 0) {
                    if (UserHelper.isSilver()) {
                        for (int i = 0; i < mPresenter.getOtcWalletInfoBeans().size(); i++) {
                            if (mPresenter.getOtcWalletInfoBeans().get(i).volume != 0
                                    || (mPresenter.getOtcWalletInfoBeans().get(i).otcAdvertVolume
                                    + mPresenter.getOtcWalletInfoBeans().get(i).otcLockVolume) != 0
                                    || mPresenter.getOtcWalletInfoBeans().get(i).bailVolume != 0) {
                                otcBeans.add(mPresenter.getOtcWalletInfoBeans().get(i));

                            }
                        }
                    } else {
                        for (int i = 0; i < mPresenter.getOtcWalletInfoBeans().size(); i++) {
                            if (mPresenter.getOtcWalletInfoBeans().get(i).volume != 0
                                    || (mPresenter.getOtcWalletInfoBeans().get(i).otcAdvertVolume
                                    + mPresenter.getOtcWalletInfoBeans().get(i).otcLockVolume) != 0) {
                                otcBeans.add(mPresenter.getOtcWalletInfoBeans().get(i));

                            }
                        }
                    }
                    if (otcBeans.size() <= 0) {
                        adapter.setEmptyView(notDataView);
                    }

                    adapter.setNewData(otcBeans);
                }
            } else if (pos == 1) {
                norBeans = new ArrayList<>();
                if (mPresenter.getNorWalletInfoBeans() != null && mPresenter.getNorWalletInfoBeans().size() > 0) {
                    for (int i = 0; i < mPresenter.getNorWalletInfoBeans().size(); i++) {
                        if (mPresenter.getNorWalletInfoBeans().get(i).volume != 0) {
                            norBeans.add(mPresenter.getNorWalletInfoBeans().get(i));
                        }
                    }
                    if (norBeans.size() <= 0) {
                        adapter.setEmptyView(notDataView);
                    }
                    adapter.setNewData(norBeans);
                }
            }
        } else {
            if (pos == 0) {
                adapter.setNewData(mPresenter.getOtcWalletInfoBeans());
            } else {
                adapter.setNewData(mPresenter.getNorWalletInfoBeans());
            }
        }
    }

    List<WalletCurrencyBean> otcSerchCoins;
    List<WalletCurrencyBean> norSerchCoins;

    public void searchCoin(String coin, boolean isSerch) {

        if (TextUtils.isEmpty(coin) && BaseApplication.isHideZeroAssests) {
            hideZeroAssests(pos);
            return;
        }
        if (pos == 0) {
            LogUtils.e("====2 searchCoin====" + coin.toString().trim() + " , isSerch " + isSerch);
            if (mPresenter.getOtcWalletInfoBeans() != null && mPresenter.getOtcWalletInfoBeans().size() > 0) {
                if (!isSerch || TextUtils.isEmpty(coin)) {
                    adapter.setNewData(mPresenter.getOtcWalletInfoBeans());
                    return;
                }
                otcSerchCoins = new ArrayList<>();
                for (int i = 0; i < mPresenter.getOtcWalletInfoBeans().size(); i++) {
                    if (mPresenter.getOtcWalletInfoBeans().get(i).getName().trim().toUpperCase().contains(coin)) {
                        otcSerchCoins.add(mPresenter.getOtcWalletInfoBeans().get(i));
                    }
                }
                adapter.setNewData(otcSerchCoins);
            }
        } else {
            if (mPresenter.getNorWalletInfoBeans() != null && mPresenter.getNorWalletInfoBeans().size() > 0) {
                if (!isSerch || TextUtils.isEmpty(coin)) {
                    adapter.setNewData(mPresenter.getNorWalletInfoBeans());
                    return;
                }
                norSerchCoins = new ArrayList<>();
                for (int i = 0; i < mPresenter.getNorWalletInfoBeans().size(); i++) {
                    if (mPresenter.getNorWalletInfoBeans().get(i).getName().trim().toUpperCase().contains(coin)) {
                        norSerchCoins.add(mPresenter.getNorWalletInfoBeans().get(i));
                    }
                }
                adapter.setNewData(norSerchCoins);
            }
        }
    }


    @Override
    protected OtcAssestPresenter createPresenter() {
        return new OtcAssestPresenter(this);
    }

    @Override
    public void onSetAdapter(List<WalletCurrencyBean> list) {

        if (list != null && list.size() <= 0) {
            adapter.setEmptyView(notDataView);
        }
        adapter.setNewData(list);

        if (!TextUtils.isEmpty(etCoin.getText().toString())) {
            searchCoin(etCoin.getText().toString().trim().toUpperCase(), true);
        }
        if (BaseApplication.isHideZeroAssests) {
            hideZeroAssests(pos);
        }

    }

    @Override
    public void onShowNoMore() {
        if (mRefreshLayout != null)
            mRefreshLayout.finishRefresh();
    }


    @Override
    public void onError(int code) {
        super.onError(code);
        if (adapter != null)
            adapter.setEmptyView(errorView);
    }

    boolean isFrist = true;

    public void refreshData() {
        if (mPresenter != null) {
            if (pos == 0) {
                if (isFrist) {
                    isFrist = false;
                }
                mPresenter.doLoadData(true);
            }
//            else if (pos == 1) {
//                if (isFrist) {
//                    isFrist = false;
//                }
//                mPresenter.doLoadData(true);
//            }

        }
    }

    public void setCheckStable(boolean isCheck) {
        cbHideZore.setChecked(isCheck);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        refreshData();
    }

    public void clearSerchContent() {
        if (etCoin != null && !TextUtils.isEmpty(etCoin.getText().toString())) {
            etCoin.setText("");
        }
    }
}
